<?php
/*
 * @Author: lokei
 * @Date: 2022-08-18 21:15:24
 * @LastEditors: lokei
 * @LastEditTime: 2022-11-16 21:28:01
 * @Description: 
 */

namespace App\Http\Controllers\Pay\Alipay;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

use Alipay\EasySDK\Kernel\Factory;
use App\Common\Alipay\Common;
use App\Models\Pay\Record\PayRecordModel;
use Illuminate\Support\Facades\Redis;

class NotifyController extends Controller
{
    public function callback($pid, Request $request)
    {
        if ($pid != null && $pid != '') {
            $config = config()->all();
            $config['database']['connections']['mysql']['database'] = $pid . '_' . env('DB_DATABASE', 'forge');
            config($config);
        }

        $options = Common::getOptions();
        Factory::setOptions($options);
        $result = Factory::payment()->common()->verifyNotify($request->all());
        if ($result && $request->input('trade_status') == 'TRADE_SUCCESS') {

            $fields = array();
            $fields['sn'] = $request->input('out_trade_no');
            if ($pid != null && $pid != '') {
                $fields['pid'] = $pid;
            }
            Redis::xAdd('pay_success', '*', $fields);

            $pay_record = PayRecordModel::where('tid', '=', $request->input('out_trade_no'))->first();
            $pay_record->status = '1';
            $pay_record->save();
            echo 'success';
        } else {
            echo 'fail';
        }
    }
}
